const { Sequelize } = require('sequelize');
require('dotenv').config();


// 初始化Sequelize实例
const sequelize = new Sequelize(
  'graduation_recruitment', // 数据库名
  'root',                   // 用户名
  '511zb',                  // 密码
  {
    host: 'localhost',
    port: 3306,
    dialect: 'mysql'
  }
);

// 测试数据库连接
const testConnection = async () => {
  try {
    await sequelize.authenticate();
    console.log('数据库连接成功！');
  } catch (error) {
    if (error.original && error.original.code === 'ER_BAD_DB_ERROR') {
      // 数据库不存在，尝试创建
      const tempSequelize = new Sequelize('', DB_USER, DB_PASS, {
        host: DB_HOST,
        port: DB_PORT,
        dialect: 'mysql',
        logging: false
      });
      try {
        await tempSequelize.query(`CREATE DATABASE IF NOT EXISTS ${DB_NAME};`);
        await tempSequelize.close();
        // 重试连接
        await sequelize.authenticate();
        console.log('数据库创建成功并已连接！');
        return;
      } catch (createError) {
        console.error('创建数据库失败:', createError);
      }
    }
    console.error('数据库连接失败详情:', error);
    console.error('连接参数:', { host: DB_HOST, port: DB_PORT, user: DB_USER, database: DB_NAME });
  }
};

testConnection();

module.exports = sequelize;